import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import AdminLayout from '../layout/AdminLayout.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/',
      component: AdminLayout,
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          redirect: '/services'
        },
        {
          path: '/users',
          name: 'users',
          component: () => import('../views/UserManageView.vue'),
          meta: { title: '用户管理' }
        },
        {
          path: '/notices',
          name: 'notices',
          component: () => import('../views/NoticeManageView.vue'),
          meta: { title: '公告管理' }
        },
        {
          path: '/services',
          name: 'services',
          component: () => import('../views/ServiceManageView.vue'),
          meta: { title: '服务管理' }
        },
        {
          path: '/activities',
          name: 'activities',
          component: () => import('../views/ActivityManageView.vue'),
          meta: { title: '活动管理' }
        }
      ]
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/services'
    }
  ]
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 判断是否需要登录权限
  if (to.meta.requiresAuth !== false) {
    // 判断用户是否已登录
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.warning('请先登录')
      next({ name: 'login' })
      return
    }
  }
  next()
})

export default router
